package com.charmzenus.smallshop.config.readWriteConfig.aspect;

/**
 * Created by zonzie on 2018/2/27.
 */


import com.charmzenus.smallshop.config.readWriteConfig.dynamicSourceConfig.DataSourceType;
import com.charmzenus.smallshop.config.readWriteConfig.dynamicSourceConfig.DynamicDataSourceHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;

/**
 * aop 配置动态切换数据源
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Around("execution(* com.charmzenus.smallshop.repository.*.select*(..)) " +
            "|| execution(* com.charmzenus.smallshop.repository.*.find*(..)) " +
            "|| execution(* org.springframework.data.jpa.repository.JpaRepository.find*(..)) " +
            "|| execution(* org.springframework.data.jpa.repository.JpaRepository.get*(..)) "
    )
    public Object setReadDataSourceType(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("------------------readAspect------------------");
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        System.out.println(signature.getMethod().getName());

        Class declaringType = signature.getDeclaringType();
        boolean annotationPresent = declaringType.isAnnotationPresent(Transactional.class);
        if (!annotationPresent) DynamicDataSourceHolder.setDataSource(DataSourceType.read.getType());
        return pjp.proceed();
    }

    @Around("execution(* com.charmzenus.smallshop.repository.*.insert*(..)) " +
            "|| execution(* com.charmzenus.smallshop.repository.*.update*(..))" +
            "|| execution(* com.charmzenus.smallshop.repository.*.add*(..))" +
            "|| execution(* org.springframework.data.jpa.repository.JpaRepository.delete*(..)) " +
            "|| execution(* org.springframework.data.jpa.repository.JpaRepository.save*(..)) "
    )
    public Object setWriteDataSourceType(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("------------------writeAspect------------------");
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Class declaringType = signature.getDeclaringType();
        boolean annotationPresent = declaringType.isAnnotationPresent(Transactional.class);



        if (!annotationPresent) DynamicDataSourceHolder.setDataSource(DataSourceType.write.getType());
        return pjp.proceed();
    }

}
